package com.cardone.persistent.builder;

import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.CollectionUtils;

/**
 * 映射生成器工具
 *
 * @author yaohaitao
 */
public class ModelUtils {
	/**
	 * 实例化对象映射
	 *
	 * @param attrs
	 *          属性集合
	 * @return 对象映射实例
	 */
	public static Model newModel(final Map<String, Object> attrs) {
		final Model model = ModelUtils.newModel();

		if (MapUtils.isNotEmpty(attrs)) {
			model.putAll(attrs);
		}

		return model;
	}

	/**
	 * 实例化对象映射
	 *
	 * @param modelArgss
	 *          对象参数
	 * @return 对象映射实例
	 */
	public static Model newModel(final ModelArgs... modelArgss) {
		return ModelUtils.put(new ModelDefault(), modelArgss);
	}

	/**
	 * 填充
	 *
	 * @param model
	 *          对象映射
	 * @param modelArgss
	 *          对象参数
	 */
	public static Model put(final Model model, final ModelArgs... modelArgss) {
		if (org.apache.commons.lang3.ArrayUtils.isEmpty(modelArgss)) {
			return model;
		}

		for (final ModelArgs modelArgs : modelArgss) {
			if (modelArgs == null) {
				continue;
			}

			if (ArrayUtils.isNotEmpty(modelArgs.getKeyBases())) {
				model.putExtend(modelArgs.getKeyPrefix(), modelArgs.getKeyBases(), modelArgs.getKeySuffix(), modelArgs.getValue());
			}

			if (!CollectionUtils.isEmpty(modelArgs.getKvMap())) {
				model.putExtend(modelArgs.getKeyPrefix(), modelArgs.getKvMap(), modelArgs.getKeySuffix());
			}

			if ((modelArgs.getO() != null) || (modelArgs.getC() != null)) {
				model.putObjectField(modelArgs);
			}
		}

		return model;
	}
}
